package com.cynteka.cyfoman.core.mail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: Sergey
 * Date: 28.07.11
 * Time: 20:26
 */
public class MailScanner {
    private String host;
    private String username;
    private String password;
    private int port = 110;
    private Properties properties = new Properties();
    private String protocol = "pop3";
    private static final String INBOX = "inbox";
    private int period = 20 * 1000;
    private static Logger logger = Logger.getLogger(MailScanner.class.getName());
    private List<MailHandler> mailHandlers;

    protected void scanMail() throws MessagingException {
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        // Get a Store object that implements the specified protocol.
        Store store = session.getStore(protocol);

        //Connect to the current host using the specified username and password.
        store.connect(host, username, password);

        //Create a Folder object corresponding to the given name.
        Folder folder = store.getFolder(INBOX);

        // Open the Folder.
        folder.open(Folder.READ_ONLY);
        // folder.fetch();

        // Get the messages from the server
        Message[] messages = folder.getMessages();
        System.out.println("Found : " + messages.length);


        // Display message.
        for (int i = 0; i < messages.length; i++) {
            System.out.println("------------ Message " + (i + 1) + " ------------");
            // Here's the big change...
            String from = InternetAddress.toString(messages[i].getFrom());
            if (from != null) {
                System.out.println("From: " + from);
            }
            String replyTo = InternetAddress.toString(
                    messages[i].getReplyTo());
            if (replyTo != null) {
                System.out.println("Reply-to: " + replyTo);
            }
            String to = InternetAddress.toString(
                    messages[i].getRecipients(Message.RecipientType.TO));
            if (to != null) {
                System.out.println("To: " + to);
            }
            String cc = InternetAddress.toString(
                    messages[i].getRecipients(Message.RecipientType.CC));
            if (cc != null) {
                System.out.println("Cc: " + cc);
            }
            String bcc = InternetAddress.toString(
                    messages[i].getRecipients(Message.RecipientType.BCC));
            if (bcc != null) {
                System.out.println("Bcc: " + to);
            }
            String subject = messages[i].getSubject();
            if (subject != null) {
                System.out.println("Subject: " + subject);
            }
            Date sent = messages[i].getSentDate();
            if (sent != null) {
                System.out.println("Sent: " + sent);
            }
            Date received = messages[i].getReceivedDate();
            if (received != null) {
                System.out.println("Received: " + received);
            }
            System.out.println();
            if (mailHandlers != null) {
                for (MailHandler mailHandler : mailHandlers) {
                    mailHandler.handleMessage(messages[i]);
                }
            }
        }

        folder.close(true);
        store.close();
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public int getPeriod() {
        return period;
    }

    public void setPeriod(int period) {
        this.period = period;
    }

    public void startScanning() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    scanMail();
                    Thread.sleep(period);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Error while scanning mail", e);
                }
            }
        });
        t.setDaemon(true);
        t.start();
    }

    public List<MailHandler> getMailHandlers() {
        return mailHandlers;
    }

    public void setMailHandlers(List<MailHandler> mailHandlers) {
        this.mailHandlers = mailHandlers;
    }
}
